package com.water.expert.extraction.controller;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.water.expert.extraction.repository.Expert;
import com.water.expert.extraction.repository.ExpertRepository;
import com.water.expert.extraction.service.ExpertService;

@RestController
@RequestMapping("/experts")
public class ExpertController {
	@Autowired
	private ExpertService expertService;
	
    @Autowired
    private ExpertRepository expertRepository;
    
    @GetMapping("/search")
    public List<Expert> searchExperts(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String title,
            @RequestParam(required = false) String companyName,
            @RequestParam(required = false) String email) {
        return expertRepository.searchExperts(name, title, companyName, email);
    }
    
    @GetMapping
    public Iterable<Expert> getAllExperts() {
        return expertService.getAllExperts();
    }

    @GetMapping("/{id}")
    public ResponseEntity<Expert> getExpertById(@PathVariable Long id) {
        return expertRepository.findById(id)
                .map(ResponseEntity::ok)
                .orElseGet(() -> ResponseEntity.notFound().build());
    }

    @PostMapping
    public Expert createExpert(@RequestBody Expert expert) {
        return expertRepository.save(expert);
    }
    
    @PutMapping("/{id}")
    public ResponseEntity<Expert> updateExpert(@PathVariable Long id, @RequestBody Expert updatedExpert) {
        return expertRepository.findById(id)
                .map(expert -> {
                    updatedExpert.setId(id);
                    return ResponseEntity.ok(expertRepository.save(updatedExpert));
                })
                .orElseGet(() -> ResponseEntity.notFound().build());
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteExpert(@PathVariable Long id) {
        return expertRepository.findById(id)
                .map(expert -> {
                    expertRepository.deleteById(id);
                    return ResponseEntity.ok().<Void>build();
                })
                .orElseGet(() -> ResponseEntity.notFound().build());
    }
}
